import { formatMessage } from 'umi-plugin-react/locale';
import { Input, Modal, Spin, Tree, Table, Button, message } from "antd";
import React from "react";
import menuCheck from "./menuCheck";
import { relatedTree } from "@/services/RelatedKnowledgeV2";
import { doRelatedQuestion, fakeAnswerRelevanceDataForHot } from "@/services/datastatistics";

class RelatedKnowledgeV2 extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      queryType: [
        {
          name: formatMessage({ id: 'utils.relatedKnowledgeV2.qaKnowledge' }),
          key: 1
        },
        {
          name: formatMessage({ id: 'utils.relatedKnowledgeV2.mapKnowledge' }),
          key: 2
        },
        {
          name: formatMessage({ id: 'utils.relatedKnowledgeV2.multipleDialog' }),
          key: 3
        },
        {
          name: formatMessage({ id: 'utils.relatedKnowledgeV2.formKnowledge' }),
          key: 4
        }
      ],
      type: 1,
      treeLoading: false,
      selectedKeys: [],
      defaultExpandedKeys: [],
      current: 1,
      size: 10,
      treeData: [],
      dataList: [],
      loading: false,
      size: 10,
      current: 1,
      total: 0,
      rowList: [],
      search: "",
      rootIds: [],
      Butloading: false
    }
  }

  componentDidMount() {
    if (this.props.onRef) {
      this.props.onRef(this)
    }
  }

  openAndInit = list => {
    this.setState({ rowList: list, visible: true }, () => {
      this.treeToData()
    })
  }

  onClose = () => {
    this.setState({
      visible: false,
      type: 1,
      treeLoading: false,
      selectedKeys: [],
      defaultExpandedKeys: [],
      current: 1,
      size: 10,
      treeData: [],
      dataList: [],
      loading: false,
      size: 10,
      current: 1,
      total: 0,
      rowList: [],
      search: "",
      rootIds: []
    })
  }

  handelOk = () => {
    const { rowList } = this.state;
    const { question } = this.props;
    if (this.props.handleModalOk) {
      this.props.handleModalOk(rowList)
    };
    if (question) {
      this.doRelationQas();
      return false;
    };
    this.onClose()
  }

  changeField = type => {
    this.setState({ type, current: 1 }, () => {
      this.treeToData()
    })
  }

  /* 类型切换-需要先加载分类-再加载表格数据 */
  treeToData = () => {
    this.setState({
      treeLoading: true
    }, async () => {
      const { type } = this.state;
      const { applicationId } = this.props;
      const res = await relatedTree({ type, applicationId })
      let data = res;
      //若类型为导图/多轮 则需要讲数据结构处理成树形 与问答知识点分类统一
      if (type == 2 || type == 3 || type == 4) {
        data = []
        for (let item of res) {
          item.name = item.rootCategoryName
          item.id = item.rootCategoryId
          item.children = item.categories ? item.categories : []
          item.parentId = 0
          data.push(item)
        }
      };

      /* 默认选中所有分类下第一个分类 */
      const selectedKeys = data && data[0] && data[0].children && data[0].children[0] ? [data[0].children[0].id] : data[0] ? [data[0].id] : []
      const categoryParentPath = data && data[0] && data[0].children && data[0].children[0] ? data[0].children[0].parentPath : data[0] ? data[0].parentPath : ''

      /* 储存知识库的id 用于加载表格数据时判断 是否选择的知识库 若选择的是知识库 入参需要修改 */
      const rootIds = data.map(item => item.id)

      this.setState({
        treeData: data,
        treeLoading: false,
        selectedKeys,
        categoryParentPath,
        defaultExpandedKeys: data && data[0] ? [data[0].id] : [],
        rootIds
      }, () => {
        this.getTableData();
      })
    })
  }


  /* 树分类的选择 */
  onSelectTree = (selectedKeys, e) => {
    this.setState({
      selectedKeys,
      categoryParentPath: e.node.props && e.node.props.parentPath ? e.node.props.parentPath : '',
      current: 1
    }, () => {
      this.getTableData();
    })
  }

  /* 获取表格数据 */
  getTableData = () => {
    this.setState({ loading: true }, async () => {
      const { type, current, size, search, selectedKeys, rootIds } = this.state;
      const { applicationId } = this.props;
      let treeId = selectedKeys && selectedKeys[0] ? selectedKeys[0] : ''
      let params = { applicationId, type, current, size, search }
      if (rootIds.indexOf(treeId) != -1 && type != 1) {
        params.rootCategoryId = treeId
      } else {
        params.categoryId = treeId
      };
      const res = await fakeAnswerRelevanceDataForHot(params)
      this.setState({
        dataList: res.records,
        total: res.total,
        loading: false
      })
    })

  }

  onExpand = expandedKeys => {
    this.setState({
      defaultExpandedKeys: expandedKeys
    })
  }

  renderAction = record => {
    const { rowList } = this.state;
    const result = rowList.some(item => {
      if (item.id === record.id || item.qaId === record.id) {
        return true;
      }
    });
    if (result) {
      return (
        <Button type="primary" onClick={() => this.unSelect(record)}>
          {formatMessage({ id: 'utils.relatedKnowledgeV2.selected' })}
          </Button>
      );
    } else {
      return <Button onClick={() => this.doSelect(record)}>{formatMessage({ id: 'utils.relatedKnowledgeV2.select' })}</Button>;
    }
  };

  handelTablePageChange = value => {
    this.setState({ current: value }, () => {
      this.getTableData();
    })
  };

  doSearch = search => {
    this.setState({ search, current: 1 }, () => {
      this.getTableData();
    });
  };

  doSelect = row => {
    const { chooseType } = this.props;
    let { rowList, type } = this.state;
    row.type = type
    if (chooseType === 'radio') {
      rowList = [row];
    } else {
      rowList.push(row);
    };
    this.setState({ rowList, }, () => {
      if (this.props.getRelatedList) {
        this.props.getRelatedList(rowList, 'Add');
      }
    });
  };

  unSelect = record => {
    const { rowList } = this.state;
    const result = rowList.filter(item => {
      return item.id !== record.id;
    });
    this.setState({ rowList: result, }, () => {
      if (this.props.getRelatedList) {
        this.props.getRelatedList(result, 'Del');
      }
    });
  };

  setRelatedList = data => {
    if (data) {
      let arr = [];
      for (let item of data) {
        arr.push({ id: item.id, basicQuestion: item.basicQuestion, type: item.type });
      }
      this.setState({ rowList: arr });
    }
  };

  doRelationQas = () => {
    const { rowList } = this.state;
    const qaIds = rowList.map((item) => item.id);
    const { question, qaId } = this.props;
    const { query } = this.state;
    if (rowList.length == 0) {
      message.info(formatMessage({ id: 'utils.relatedKnowledgeV2.selectKnowledgeTip' }))
      return false
    };
    let qaType = "";
    switch (rowList[0].type) {
      case 1:
        qaType = "qa";
        break;
      case 2:
        qaType = "atlasNode";
        break;
      case 3:
        qaType = "dialog";
        break;
      case 4:
        qaType = "form";
        break;
      default:
        qaType = "qa";
        break;
    };
    let obj = {
      qaIds,
      question,
      targetId: qaId,
      qaType,
    };
    this.setState({
      Butloading: true
    }, async () => {
      const res = await doRelatedQuestion(obj);
      this.setState({ Butloading: false });
      this.onClose()
      if (this.props.refreshList) {
        this.props.refreshList()
      }
    })
  };



  render() {
    const { visible, queryType, type, treeLoading, selectedKeys, defaultExpandedKeys, treeData, dataList, loading, size, current, total, Butloading } = this.state;

    const renderTreeNode = (data) => {
      return data.map(item => {
        if (item.children && item.parentId == '0') {
          return (
            <Tree.TreeNode title={item.name} key={item.id} parentId={item.parentId} parentPath={item.parentPath}>
              {renderTreeNode(item.children)}
            </Tree.TreeNode>
          )
        } else {
          return <Tree.TreeNode title={item.name} key={item.id} parentId={item.parentId} parentPath={item.parentPath} />
        }
      })
    }

    const columns = [
      {
        title: formatMessage({ id: 'utils.relatedKnowledgeV2.basicQuestion' }),
        dataIndex: 'basicQuestion',
        key: 'basicQuestion',
        width: 200,
      },
      {
        title: formatMessage({ id: 'utils.relatedKnowledgeV2.category' }),
        dataIndex: 'categoryNamePath',
        key: 'categoryNamePath',
        width: 200,
      },
      {
        title: formatMessage({ id: 'utils.relatedKnowledgeV2.action' }),
        dataIndex: 'action',
        key: 'action',
        width: 100,
        render: (text, record) => {
          return this.renderAction(record);
        },
      },
    ];


    return (
      <Modal
        title={formatMessage({ id: 'utils.relatedKnowledgeV2.selectRelatedQuestion' })}
        placement="right"
        closable
        onCancel={this.onClose}
        visible={visible}
        width={'85%'}
        onOk={this.handelOk}
        destroyOnClose
        confirmLoading={Butloading}
      >
        {/* 类型 */}
        <div style={{ display: 'flex' }}>
          <div style={{ width: 160, marginRight: 10, background: 'rgb(247, 248, 250)', textAlign: 'center' }}>
            {
              queryType.map(item => {
                return <div
                  key={item.key}
                  style={{
                    cursor: 'pointer',
                    margin: '0 0 16px 0',
                    padding: '8px 24px',
                    color: type == item.key ? '#3e5bff' : '',
                    background: type == item.key ? '#E6ECF6' : '',
                    borderRight: '2px solid',
                    borderColor: type == item.key ? '#3e5bff' : 'rgb(247, 248, 250)',
                  }}
                  onClick={() => this.changeField(item.key)}
                >
                  {item.name}
                </div>
              })
            }
          </div>

          {/* 分类 */}
          <Spin spinning={treeLoading}>
            <div style={{ width: 250, height: 500, overflow: 'auto' }}>
              <Tree defaultExpandAll={true} selectedKeys={selectedKeys} expandedKeys={defaultExpandedKeys} onSelect={this.onSelectTree} onExpand={this.onExpand}>
                {renderTreeNode(treeData)}
              </Tree>
            </div>
          </Spin>

          {/* 表格数据 */}
          <div style={{ width: 'calc(100% - 340px)', marginLeft: 10 }}>
            <Input.Search
              placeholder={formatMessage({ id: 'utils.relatedKnowledgeV2.inputPlaceholder' })}
              onSearch={this.doSearch}
              style={{ width: '300px', margin: '10px' }}
            />

            <Table
              dataSource={dataList}
              columns={columns}
              loading={loading}
              bordered
              rowKey={'id'}
              pagination={{
                pageSize: size,
                onChange: this.handelTablePageChange,
                current,
                total,
              }}
              scroll={{ y: 400 }}
            />
          </div>
        </div>

      </Modal>
    )
  }
}

export default RelatedKnowledgeV2